<template>
  <div class="material-list-container">
    <el-card shadow="never">
      <template #header>
        <div class="table-header">
          <div class="left">
            <h3>资料列表</h3>
          </div>
          <div class="right">
            <el-button type="primary" @click="refresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="资料名称">
          <el-input 
            v-model="searchForm.title" 
            placeholder="输入资料名称"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="分类">
          <el-select 
            v-model="searchForm.categoryId" 
            placeholder="选择分类"
            clearable
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="选择状态"
            clearable
          >
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 资料表格 -->
      <el-table
        :data="materials"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="资料名称" min-width="200" />
        <el-table-column label="分类" width="120">
          <template #default="{row}">
            <el-tag>{{ row.category?.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="标签" width="180">
          <template #default="{row}">
            <el-tag
              v-for="tag in row.tags"
              :key="tag.id"
              size="small"
              style="margin-right: 5px"
            >
              {{ tag.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="downloads" label="下载量" width="100" />
        <el-table-column label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="statusType[row.status]">
              {{ statusText[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{row}">
            <el-button 
              size="small" 
              @click="viewDetail(row.id)"
            >
              详情
            </el-button>
            <el-dropdown @command="handleCommand($event, row.id)">
              <el-button size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="approve" v-if="row.status !== 'approved'">
                    通过审核
                  </el-dropdown-item>
                  <el-dropdown-item command="reject" v-if="row.status !== 'rejected'">
                    拒绝审核
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          @current-change="handlePageChange"
          layout="total, prev, pager, next"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMaterials, updateMaterialStatus, deleteMaterial } from '@/api/admin'
import { getCategories } from '@/api/material'
import { Refresh, ArrowDown } from '@element-plus/icons-vue'

const router = useRouter()

// 状态文本映射
const statusText = {
  pending: '待审核',
  approved: '已通过',
  rejected: '已拒绝'
}

// 状态标签类型
const statusType = {
  pending: '',
  approved: 'success',
  rejected: 'danger'
}

// 搜索表单
const searchForm = ref({
  title: '',
  categoryId: '',
  status: ''
})

// 分页
const pagination = ref({
  current: 1,
  size: 20,
  total: 0
})

// 数据
const materials = ref([])
const categories = ref([])
const loading = ref(false)

// 加载资料列表
const loadMaterials = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm.value,
      page: pagination.value.current,
      size: pagination.value.size
    }
    
    const res = await getMaterials(params)
    materials.value = res.data.items
    pagination.value.total = res.data.total
  } catch (error) {
    console.error('加载资料列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载分类
const loadCategories = async () => {
  try {
    const res = await getCategories()
    categories.value = res.data
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadMaterials()
}

// 刷新
const refresh = () => {
  loadMaterials()
}

// 分页变化
const handlePageChange = () => {
  loadMaterials()
}

// 查看详情
const viewDetail = (id) => {
  router.push(`/material/${id}`)
}

// 处理操作命令
const handleCommand = async (command, id) => {
  try {
    switch (command) {
      case 'approve':
        await updateMaterialStatus(id, { status: 'approved' })
        ElMessage.success('资料已通过审核')
        break
      case 'reject':
        await updateMaterialStatus(id, { status: 'rejected' })
        ElMessage.success('资料已拒绝审核')
        break
      case 'delete':
        await ElMessageBox.confirm('确定删除此资料吗？', '警告', {
          type: 'warning'
        })
        await deleteMaterial(id)
        ElMessage.success('资料已删除')
        break
    }
    
    // 刷新列表
    loadMaterials()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error(error.message || '操作失败')
    }
  }
}

onMounted(() => {
  loadMaterials()
  loadCategories()
})
</script>

<style scoped>
.material-list-container {
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>